package htmodels

import (
	"github.com/astaxie/beego/orm"
	"shuxianghui/models"
)

func HTMessagesAdd(messages *models.Messages) error {
	o := orm.NewOrm()
	_, err := o.Insert(messages)
	return err
}

func HTMessagesGetDetail(messages *models.Messages) error {
	o := orm.NewOrm()
	return o.Read(messages)
}

func HTMessagesGetCount(search string, searchFiled string , MesageStatus int, Type int,reciveId int) (int64, error) {
	o := orm.NewOrm()
	m := models.Messages{}
	qb:=o.QueryTable(m.TableName())
	if reciveId!=0{
		qb=qb.Filter(m.FN_ReceiveId(),reciveId)
	}else{
		qb=qb.Filter(searchFiled + "__icontains", search)
	}
	count, err := qb.Filter(m.FN_MesageStatus(), MesageStatus).Filter(m.FN_Type(), Type).Count()
	return count, err
}

func HTMessagesGetList(messagess *[]models.Messages, fields []string , MesageStatus int, Type int, offset int64, limit int, search string, searchFiled string, orderby string,reciveId int,hasType bool) error {
	o := orm.NewOrm()
	m := models.Messages{}
	qb:=o.QueryTable(m.TableName())
	if reciveId!=0{
		qb=qb.Filter(m.FN_ReceiveId(),reciveId)
	}else{
		qb=qb.Filter(searchFiled + "__icontains", search)
	}
	if hasType{
		qb=qb.Filter(m.FN_Type(), Type)
	}
	_, err := qb.Filter(m.FN_MesageStatus(), MesageStatus).OrderBy(orderby).Offset(offset).Limit(limit).All(messagess, fields...)
	return err
}

func HTMessagesDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.Messages{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}
func HTMessagesStatusChange(Ids []int64, status int) (int64, error) {
	o := orm.NewOrm()
	m := models.Messages{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Update(orm.Params{
		m.FN_MesageStatus(): status,
	})
	return count, err
}
func HTMessagesUpdate(messages *models.Messages) error {
	o := orm.NewOrm()
	_, err := o.Update(messages)
	return err
}